Home:ALL Converter>PHP MongoDB find with multiple "AND" conditions?

PHP MongoDB find with multiple "AND" conditions?

Ask Time:2016-03-21T20:10:05         Author:Gwen Wing

Json Formatter

After hours of experimentations and readings, I cannot find a solution to this problem:

I want to do a MongoDB->find($query) with multiple AND conditions.

For instance, say I want id = 5 and a < 6 and a > 2 and b > 10 and b < 20

I was expecting $query to be:

$query = array("id" => 5,
   "a" => array('$gt' => 2,  
           '$lt' => 6),
   "b" => array('$gt' => 10,
           '$lt' => 20))

But this returns empty results with my DB

I tried various syntaxes such as:

$query = array("id" => 5,
          array( "a" => array('$gt' => 2,
              '$lt' => 6),
       "b" => array('$gt' => 10,
             '$lt' => 20)))

But this fails too.

Also tried with "$AND" variants, no luck.

Is it possible to "mix" several AND conditions in PHP-MongoDB find() requests?

Author:Gwen Wing,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/36130643/php-mongodb-find-with-multiple-and-conditions
Wan B. :

I've just tested this using MongoDB PHP driver v1.6.11 (PHP-5.5.9). The test data are as below\n\ndb.collection.insert({id:5, a:4, b:15})\ndb.collection.insert({id:9, a:4, b:15})\ndb.collection.insert({id:5, a:4, b:20})\n\n\nUsing PHP code snippet: \n\n$condition = array(\n '$and' => array(\n array(\n \"id\" => 5,\n \"a\" => array('$gt' => 2, '$lt' => 6),\n \"b\" => array('$gt' => 10, '$lt' => 20)\n )\n )\n);\n$docs = $coll->find($condition);\n\nforeach( $docs as $o=> $doc) {\n echo json_encode($doc);\n}\n\n\nThe above returns only the first document sample. This indicates that $and should work as expected. I've also tested without $and, i.e. : \n\n$condition = array(\n \"id\" => 5,\n \"a\" => array('$gt' => 2, '$lt' => 6),\n \"b\" => array('$gt' => 10, '$lt' => 20)\n);\n\n\nWhich also works the same. Try checking your dataset, whether there is a document matching your criteria. ",
2016-03-31T03:51:38
yy